package com.zone.component_setting.repository

import android.util.Log
import androidx.paging.PageKeyedDataSource
import com.zone.core.coroutine.ErrorHandle
import com.zone.core.coroutine.request
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers

class PageDataSource<T>(private val block: suspend CoroutineScope.(pageNum: Int, pageSize: Int) -> List<T>) :
    PageKeyedDataSource<Int, T>() {

    private val onError: ErrorHandle = {
        it is Exception
    }

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, T>
    ) {
        request(Dispatchers.IO, error = onError) {
            val bean = block(0, params.requestedLoadSize)
            Log.d("TAG", "loadInitial: ===========" + bean)
            callback.onResult(bean, 0, 2)
        }
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, T>) {
        Log.d("TAG", "loadAfter: ===========" + params.key + 1)
        request(Dispatchers.IO, error = onError) {
            val bean = block(params.key, params.requestedLoadSize)
            callback.onResult(bean, params.key + 1)
        }
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, T>) {
        Log.d("TAG", "loadBefore: ===========" + (params.key - 1))
        request(Dispatchers.IO, error = onError) {
            val bean = block(params.key, params.requestedLoadSize)
            callback.onResult(bean, params.key - 1)
        }
    }
}